import datetime
import os
import re
import time
import threading
import locale


from Extend.GrandClass import GrandClass
from Extend.ListAdvancedMethod import DateMethod
from Extend.Log import LogMethod
from Extend.NoSql import NoSqlDataGet
from Extend.FileMethod import FileExtend
from Extend.NoSql import Heart


class LogFile:

    # 从文件获取今天的数据
    @staticmethod
    def getTodayLog():
        today = datetime.datetime.now().strftime('%F')
        return LogFile.getLog(today)

    # 获取昨天的数据
    @staticmethod
    def getYesterdayLog():
        yesterday = (datetime.datetime.now() - datetime.timedelta(days=1)).strftime('%F')
        return LogFile.getLog(yesterday)

    # 写入更新的数据，累加进去
    @staticmethod
    def writeTodayLog(content, path):
        today = datetime.datetime.now().strftime('%F')
        return LogFile.writeLog(today, content, path)

    # 写入昨天的数据
    @staticmethod
    def writeYesterdayLog(content, path):
        yesterday = (datetime.datetime.now() - datetime.timedelta(days=1)).strftime('%F')
        return LogFile.writeLog(yesterday, content, path)

    @staticmethod
    def writeLog(day, content, path):
        LogFile.dateSort(content)
        LogFile.replaceZero(content)
        real_content = LogFile.listDictToContent(content)
        file_name = os.path.join(path, day + ".log")
        FileExtend.appendFile(file_name, real_content)

    @staticmethod
    def replaceZero(content):
        for element in content:
            temp_date = element['CreateDate']
            temp_date1 = temp_date[0:temp_date.find(":")]
            temp_date2 = temp_date[temp_date.find(":"):]
            temp_date1 = re.sub(r'\d+', lambda ele: str(int(ele.group())), temp_date1)
            element['CreateDate'] = temp_date1 + temp_date2

    @staticmethod
    def listDictToContent(content):
        real_content = []
        for x in content:
            real_content.append("{OrderNO}\t{Status}\t{CreateDate}".format(**x))
        real_content = '\n'.join(real_content) + "\n"
        return real_content

    @staticmethod
    def dateSort(content: list):
        for element in content:
            element['CreateDate'] = DateMethod.dateToInt(element['CreateDate'])
        content.sort(key=(lambda ele: ele['CreateDate']))
        for element in content:
            element['CreateDate'] = DateMethod.intToDate(element['CreateDate'])

    @staticmethod
    def getLog(day):
        file_name = os.path.join(LogFileControl.path, day + ".log")
        content = FileExtend.readFile(file_name)
        line_content = content.split('\n')
        result = []
        for line in line_content:
            temp_line = line.split('\t')
            if len(temp_line) != 3:
                continue
            result.append({"OrderNO": temp_line[0], "CreateDate": temp_line[2], "Status": temp_line[1]})
        return result


class LogFileControl(GrandClass):

    def __init__(self, path: str):
        super().__init__()
        self.path = path

    # 循环主逻辑
    def startMonitors(self):
        while Heart.getMeHeart(self.__class__.__name__, ):
            super().startMonitors()
            try:
                # st = time.time()
                # 处理昨天剩余的
                difference = NoSqlDataGet.GetYesterdayLog()
                if len(difference) > 0:
                    LogFile.writeYesterdayLog(difference, self.path)
                    NoSqlDataGet.SetYesterdayLog(difference)
                # 处理今天的
                difference = NoSqlDataGet.GetTodayLog()
                if len(difference) > 0:
                    LogFile.writeTodayLog(difference, self.path)
                    NoSqlDataGet.SetTodayLog(difference)
                # print('写入本地日志耗时%.2f秒' % (time.time() - st))
            except Exception as err:
                LogMethod.addLog([14, "写入本地日志失败！", str(err)])
                Heart.setMeStat(self.__class__.__name__, False)
                # Heart.setMeHeart(self.__class__.__name__, False)
                return
            time.sleep(1)  # 工作太快协程会不检测服务器状态-
        Heart.setMeStat(self.__class__.__name__, False)
        # print('结束关闭')


if __name__ == '__main__':
    dc = LogFileControl('\\\\172.16.200.147\\LogFiles')
    dc.start()
